//
//  HJRefreshControl.swift
//  zhangmiSinweibo
//
//  Created by zhangmi on 16/5/28.
//  Copyright © 2016年 Paramount Pictures. All rights reserved.
//

import SnapKit

enum RefreshStatue: Int{
    case Normal      //普通状态
    case Pulling     //准备刷新状态
    case Refreshing  //正在刷新
}

private let refreshViewHeight: CGFloat = 60

class HJRefreshControl: UIControl {
    
    var statue: RefreshStatue = .Normal {
        didSet {
            switch statue {
            case .Normal:
                print("下拉刷新")
                //更新UI
                //显示箭头
                arrowicon.hidden = false
                //转动小菊花
                indicatorView.stopAnimating()
                tipLabel.text = "下拉刷新"
                UIView.animateWithDuration(0.25, animations: { 
                    self.arrowicon.transform = CGAffineTransformIdentity
                })
                
                if oldValue == .Refreshing {
                    
                    UIView.animateWithDuration(0.25, animations: { 
                        //必须之前的状态是refreshing才能减
                        //scrollView的顶部的距离, 创造悬停的效果
                        var inset = self.scrollView!.contentInset
                        //增加刷新的控件的高度
                        inset.top -= refreshViewHeight
                        //赋值给scrollView
                        self.scrollView?.contentInset = inset
                    })
                }
                
            case .Pulling:
                print("准备刷新")
                tipLabel.text = "准备刷新"
                UIView.animateWithDuration(0.25, animations: {
                    self.arrowicon.transform = CGAffineTransformMakeRotation(CGFloat(M_PI))
                    
                    
                })
            case .Refreshing:
                print("正在刷新")
                    tipLabel.text = "正在刷新"
                    //隐藏箭头
                    arrowicon.hidden = true
                   //转动小菊花
                   indicatorView.stopAnimating()
                
                //请求网络数据 给观察的对象主动发送对应类型的事件
                sendActionsForControlEvents(.ValueChanged)
                
                UIView.animateWithDuration(0.25, animations: { 
                    //scrollView的顶部的距离, 创造悬停的效果
                    var inset = self.scrollView!.contentInset
                    //增加刷新控件的高度
                    inset.top += refreshViewHeight
                    //赋值给scrollView
                    self.scrollView?.contentInset = inset
                })
                //记录上一次的状态
                //lastStatue = statue

            }
        }
    }
    
    func endRefreshing() {
//         statue = .Normal
        //执行延迟
        
        //        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(<#delayInSeconds#> * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        //    <#code to be executed after a specified delay#>
        //    });
        
        let time_t = dispatch_time(DISPATCH_TIME_NOW, Int64(Double(NSEC_PER_SEC) * 0.9))
        dispatch_after(time_t, dispatch_get_main_queue()) {
            self.statue = .Normal

        
    }
}
    
    override init(frame: CGRect) {
        let rect = CGRect(x: 0, y: -refreshViewHeight, width: ScreenWidth, height: refreshViewHeight)
        super.init(frame: rect)
        backgroundColor = UIColor.yellowColor()
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //键值观察的响应方法
    override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
//        print(change)
        //1.获取父视图的垂直方向的位移
        let offsetY = scrollView?.contentOffset.y ?? 0
        //2.和 -124比较
        
        //有被拖拽
        if scrollView!.dragging {
            if statue == .Pulling && offsetY > -124 {
                //普通状态
                statue = .Normal
            }else if statue == .Normal && offsetY < -124 {
                //达到临界点, 变为等待刷新的状态
                statue = .Pulling
            }
        } else {
            //没有被拽动 && 并且状态是 等待刷新状态, 修改为刷新状态
            if statue == .Pulling {
                statue = .Refreshing
            }
        }
    }
    
    //将要移动到父视图上
    override func willMoveToSuperview(newSuperview: UIView?) {
        super.willMoveToSuperview(newSuperview)
        //获取tableView
        if let myFather = newSuperview as? UIScrollView {
            //如果父视图是scrollView及其子类
            //获取父视图的垂直方向的位移
            // KVO  通过键值方式观察对象的属性变化
            scrollView = myFather
            scrollView?.addObserver(self, forKeyPath: "contentOffset", options: .New, context: nil)
        }
    }
    
    
    private func setupUI() {
        addSubview(arrowicon)
        addSubview(tipLabel)
        addSubview(indicatorView)
        
        arrowicon.snp_makeConstraints { (make) -> Void in
            //水平居中 向左偏移 30
            make.centerX.equalTo(self.snp_centerX).offset(-30)
            make.centerY.equalTo(self.snp_centerY)
        }
        
        tipLabel.snp_makeConstraints { (make) -> Void in
            make.left.equalTo(arrowicon.snp_right)
            make.centerY.equalTo(self.snp_centerY)
        }
        
        
        indicatorView.snp_makeConstraints { (make) -> Void in
            make.center.equalTo(arrowicon.snp_center)
        }
    }
    
    //懒加载子视图
    //记录父视图的属性
    var scrollView: UIScrollView?
    private lazy var arrowicon: UIImageView = UIImageView(image: UIImage(named: "tableview_pull_refresh"))
    private lazy var tipLabel: UILabel = UILabel(title: "下拉刷新", font: 14, textColor: UIColor.darkGrayColor())
    private lazy var indicatorView: UIActivityIndicatorView = UIActivityIndicatorView(activityIndicatorStyle: .Gray)
    
    
    deinit {
        //移除键值观察
        scrollView?.removeObserver(self, forKeyPath: "contentOffset")
    }
}

